import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:stage6_examination/constants/colors.dart';
import 'package:stage6_examination/pages/message/index.dart';
import 'package:stage6_examination/pages/mine/index.dart';
import 'package:stage6_examination/pages/task/index.dart';
import 'package:stage6_examination/routes/index.dart';
import 'package:stage6_examination/utils/eventbus.dart';
import 'package:stage6_examination/utils/token.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  int currentIndex = 0;

  List tabBarList = [
    {'title': '任务', 'icon': 'assets/task.svg'},
    {'title': '消息', 'icon': 'assets/message.svg'},
    {'title': '我的', 'icon': 'assets/mine.svg'},
  ];

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });

    eventBus.on<TokenInvalidEvent>().listen((event) {
      Navigator.pushNamed(context, AppRouter.login);
    });
  }

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (final (index, item) in tabBarList.indexed) {
      items.add(
        BottomNavigationBarItem(
          icon: SvgPicture.asset(item['icon'],
              colorFilter: currentIndex == index ? ColorFilter.mode(
              AppColors.primary,
                BlendMode.srcIn, // 关键混合模式
            ) : null
          ),
          label: item['title'],
        ),
      );
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: currentIndex,
          children: [TaskPage(), MessagePage(), MinePage()],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: barItemList(),
        enableFeedback: false, // 禁用点击反馈音效
        currentIndex: currentIndex,
        selectedItemColor: AppColors.primary,
        unselectedItemColor: Colors.black,
        selectedLabelStyle: TextStyle(fontSize: 12), // 选中时文字大小
        unselectedLabelStyle: TextStyle(fontSize: 12), 
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      )
    );
  }
}